package cn.erhu.tools.tar;

import org.xeustechnologies.jtar.TarEntry;
import org.xeustechnologies.jtar.TarInputStream;

import java.io.*;

/**
 * 读取.tar文件
 * <p/>
 * User: erhu
 * Date: 13-10-17
 * Time: 上午11:52
 */
public class ReadTar {
    public static void main(String[] args) throws Exception {


        String tar_file = "/Users/erhu/Downloads/u_kzncd6aaf3ff.tar";
        String dest_folder = "/Users/erhu/Downloads/tmp/";

        checkTarFileName(tar_file);

        TarInputStream tis = new TarInputStream(new BufferedInputStream(new FileInputStream(tar_file)));
        TarEntry entry;
        while ((entry = tis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[2048];
            String file_name = dest_folder + entry.getName();
            int index = file_name.lastIndexOf("/");

            System.out.println(file_name.substring(0, index));

            File folder = new File(file_name.substring(0, index));
            if (!folder.exists()) {
                folder.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(dest_folder + "/" + entry.getName());
            BufferedOutputStream dest = new BufferedOutputStream(fos);
            while ((count = tis.read(data)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        tis.close();
    }

    private static boolean checkTarFileName(String _tar_file_name) {

        int last_dot_index = _tar_file_name.lastIndexOf(".");
        if (last_dot_index > 0) {
            String extension_name = _tar_file_name.substring(last_dot_index, _tar_file_name.length());
            return extension_name.equalsIgnoreCase(".tar");
        }

        return false;
    }
}
